import { delay, put, takeLatest, all, call } from "redux-saga/effects";
import * as user from "@services/user";
/**
 * 登录事务处理(异步)
 */
export function* login(action) {
  const data = action.data;
  console.log("start login");
  console.log(action);
  try {
    if (data.data.username === "" || data.data.password === "") {
      throw new Error("字段不能为空");
    }
    yield delay(1000);
    const token = yield call(user.login, data.data);
    yield put({
      type: "LOGIN_SUCCESS",
      token
    });
    window.localStorage.setItem("username", data.data.username);
    yield data.history.push("/");
  } catch (error) {
    yield put({ type: "LOGIN_FAILURE", error: [error.message] });
  }
}

export function* watchLoginAsyn() {
  yield takeLatest("LOGIN", login);
}
